package com.powerwyx.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powerwyx.apicommon.model.entity.UserInterfaceInfo;
import com.powerwyx.project.common.ErrorCode;
import com.powerwyx.project.exception.BusinessException;
import com.powerwyx.project.mapper.UserInterfaceInfoMapper;
import com.powerwyx.project.service.UserInterfaceInfoService;
import org.springframework.stereotype.Service;

/**
 * @author 17585
 * @description 针对表【user_interface_info】的数据库操作Service实现
 * @createDate 2024-08-03 14:16:28
 */
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo>
        implements UserInterfaceInfoService {

    @Override
    public void validUserInterfaceInfo(UserInterfaceInfo userInterfaceInfo, boolean add) {

        if (userInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = userInterfaceInfo.getId();
        Long userId = userInterfaceInfo.getUserId();
        Long interfaceInfoId = userInterfaceInfo.getInterfaceInfoId();
        Integer totalNum = userInterfaceInfo.getTotalNum();
        Integer leftNum = userInterfaceInfo.getLeftNum();
        Integer status = userInterfaceInfo.getStatus();

        // 创建时，所有参数必须非空
        if (add) {
            if (userId <= 0 || interfaceInfoId <= 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户或接口不存在");
            }
        }
        if (leftNum <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口调用次数不足");
        }
    }

    /**
     * @param interfaceId
     * @param userId
     * @return
     */
    @Override
    public boolean invokeCount(long interfaceId, long userId) {
        if (interfaceId <= 0 || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        UpdateWrapper<UserInterfaceInfo> updateWrapper = new UpdateWrapper<UserInterfaceInfo>()
                .eq("interfaceInfoId", interfaceId)
                .eq("userId", userId)
                .gt("leftNum", 0)//增加乐观锁，防止并发时的超卖问题
                .setSql("leftNum = leftNum - 1,totalNum = totalNum + 1");
        return update(updateWrapper);
    }

}




